<template>
  <div class="add-edit-timed-task-form">
    <!-- :wrapper-col="{ span: 10 }" -->
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      @finish="handleFinish"
      :labelCol="{ style: { width: '84px', marginRight: '21px' } }"
      :colon="false"
      labelAlign="right"
    >
      <a-form-item label="任务名称" name="task_name">
        <a-input v-model:value.trim="formData.task_name" class="w-[440px]" :maxlength="30" placeholder="请输入任务名称">
        </a-input>
      </a-form-item>

      <a-form-item label="采集资源" name="collect_id">
        <a-select
          v-model:value="formData.collect_id"
          :options="COLLECT_RESOURCES"
          placeholder="请选择采集资源"
          :field-names="{ label: 'name', value: 'id' }"
          class="w-[440px]"
          :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
        >
        </a-select>
      </a-form-item>

      <a-form-item label="采集范围" name="collect_scope">
        <a-radio-group v-model:value="formData.collect_scope">
          <a-radio :value="1" class="mr-[33px]">采集当天</a-radio>
          <a-radio :value="2" class="mr-[33px]">采集本周</a-radio>
          <a-radio :value="3" class="mr-[33px]">采集本月</a-radio>
          <a-radio :value="4" class="mr-[33px]">采集全部</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="定时规则" name="task_rule">
        <a-radio-group v-model:value="formData.task_rule" @change="timingRuleChangeHandle">
          <a-radio :value="1" class="mr-[61px]">每日</a-radio>
          <a-radio :value="2" class="mr-[61px]">每周</a-radio>
          <a-radio :value="3" class="mr-[61px]">每月</a-radio>
        </a-radio-group>
        <a-form-item-rest>
          <WeekCheckboxGroup v-model:new-value="formData.weekArr" v-if="formData.task_rule === 2" />
          <a-form-item name="month" class="month-input" v-if="formData.task_rule === 3">
            <a-input
              v-model:value="formData.month"
              placeholder="请输入每月定时采集日期  使用逗号“,”分隔"
              class="w-[440px]"
            >
            </a-input>
          </a-form-item>

          <TimingRuleTable v-model:new-value="formData.timeArr" class="w-[440px]" />
        </a-form-item-rest>
      </a-form-item>

      <a-form-item label="内容分发" name="content_distribute">
        <a-radio-group v-model:value="formData.content_distribute">
          <a-radio :value="1" class="mr-[33px]">立即上线</a-radio>
          <a-radio :value="2" class="mr-[33px]">下线状态</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 价格设定 -->
      <PriceSetting v-model:price_set="formData.price_set" v-model:price="formData.price" />

      <a-form-item label="排序" name="order" class="sort-input">
        <a-input-number
          v-model:value="formData.order"
          :min="0"
          :max="999999"
          placeholder="请输入序号"
          class="w-[240px]"
          @blur="
            () => {
              if (!formData.order) formData.order = 0
            }
          "
        />
      </a-form-item>

      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="formData.status">
          <a-radio :value="1" class="mr-[127px]">启用</a-radio>
          <a-radio :value="2">禁用</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-divider />

      <a-form-item style="margin-right: 0">
        <a-button type="primary" html-type="submit" :loading="confirmLoading">保存采集任务</a-button>
        <a-button style="margin-left: 10px" @click="handleBack">返回</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup name="AddEditTimedTaskForm">
import WeekCheckboxGroup from './components/week-checkbox-group/index.vue'
import TimingRuleTable from './components/timing-rule-table/index.vue'
import type { TimingRuleTableDataType } from './components/timing-rule-table/type'
import { ref, computed, reactive, onMounted } from 'vue'
import { COLLECT_RESOURCES, getCollectResources } from '@/stores/modules/collect-manage/select-data-source'
import { Modal, message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import PriceSetting from '../components/collect-operate/components/price-setting/index.vue'
import type { PriceSettingType, GoldCoinType } from '../components/collect-operate/components/price-setting/type'
import { useRoute, useRouter } from 'vue-router'
import apis from '@/apis'
// api
const { addTask, getTask, updateTask } = apis.collectManage
// form-data
const formRef = ref()

const taskId = ref()
type StrType = string | null
type NumType = number | null
type FormDataType = {
  task_name: StrType
  collect_id: string | undefined
  collect_scope: NumType
  task_rule: NumType
  task_time: string[]
  timeArr: TimingRuleTableDataType
  weekArr: string[]
  collect_date: string | undefined
  month: StrType
  content_distribute: NumType
  price_set: PriceSettingType
  coin_set: number[]
  price: GoldCoinType
  order: number
  status: number
  id?: string
}
let formData = reactive<FormDataType>({
  task_name: null,
  collect_id: undefined,
  collect_scope: 1,
  task_rule: 1,
  task_time: [],
  collect_date: undefined,
  timeArr: [{ time: undefined }],
  weekArr: [],
  month: null,
  content_distribute: 1,
  price_set: 1,
  coin_set: [],
  price: '',
  order: 0,
  status: 1
})
const monthRuleReg = /^([1-9]|[1-2][0-9]|3[0-1])(,([1-9]|[1-2][0-9]|3[0-1]))*$/
const handleMonthCheck = (rule: any, value: any, callback: any) => {
  if (!value) {
    return Promise.reject('请输入定时采集日期')
  } else if (!monthRuleReg.test(value)) {
    return Promise.reject('定时采集日期只能 1~31， 多个日期使用英文逗号 "," 隔开')
  } else {
    return Promise.resolve()
  }
}
// form-rule
const rules: Record<string, Rule[]> = {
  task_name: [{ required: true, trigger: 'blur' }],
  collect_id: [{ required: true, trigger: 'change' }],
  weekArr: [{ required: true, trigger: 'change', message: '请选择采集日期' }],
  month: [
    {
      required: true,
      validator: handleMonthCheck,
      trigger: 'blur'
    }
  ]
}

// 定时规则 切换 清空相关字段值
const timingRuleChangeHandle = () => {
  formData.timeArr = [{ time: '00:00:00' }] // 时间选择 table
  formData.month = null // 月
  formData.weekArr = []
}

// form-handle
const confirmLoading = ref<boolean>(false)

const router = useRouter()
const handleBack = () => {
  formRef.value.resetFields()
  router.back()
}

// 编辑反显
const route = useRoute()
const { id } = route.params
const getEditFormData = () => {
  console.log('~~~~~~~~id:', id)
}
id && getEditFormData()

// 组装提交数据
const getSubmitData = () => {
  if (formData.task_rule === 2) {
    formData.collect_date = formData.weekArr.join(',')
  } else if (formData.task_rule === 3) {
    formData.collect_date = formData.month as string
  }
  console.log('formData.timeArr: ', formData.timeArr)
  if (formData.timeArr.length > 0) {
    formData.task_time = formData.timeArr.map((item: any) => {
      console.log('item: ', item.time)
      return item?.time ?? '00:00:00'
    })
    const flag = formData.task_time.some((item) => !item)
    if (flag) formData.task_time = []
  }
  if (formData.price_set === 2) {
    formData.coin_set = [+formData.price]
  } else if (formData.price_set === 3) {
    console.log(formData.price, 'formData.price')
    formData.coin_set = []
    formData.price.split(',').forEach((item: any) => {
      formData.coin_set.push(+item)
    })
  }
  formData.order = +formData.order
  // const submitData = { ...formData }
  const { timeArr, month, weekArr, ...params } = formData
  return params
}
//重置表单数据
const reset = () => {
  formRef.value.resetFields()
  formData.coin_set = []
  formData.task_time = []
  formData.collect_date = ''
  formData.timeArr = [{ time: '00:00:00' }]
}
// 提交
const handleFinish = (values: FormDataType) => {
  if (!taskId.value) {
    const params = getSubmitData()
    console.log('params: ', params)
    addTask({ ...params })
      .then(() => {
        message.success('保存成功')
        reset()
        console.log(formData, '最新的formData')
        router.back()
      })
      .catch(() => {
        // reset()
      })
  } else {
    const params = getSubmitData()
    params.id = taskId.value
    updateTask({ ...params }).then(() => {
      message.success('编辑成功')
      reset()
      console.log(formData, '最新的formData')
      router.back()
    })
  }
}
//获取任务详情
const getTaskDetail = () => {
  getTask({ id: taskId.value }).then((res: any) => {
    console.log('res详情: ', res.task)
    if (res.task.coin_set.length <= 0) {
      res.task.price = undefined
    } else {
      res.task.price = res.task.coin_set.join(',')
    }
    if (res.task.task_rule === 2) {
      res.task.collect_date = res.task.collect_date.split(',')
    }
    if (res.task.task_time.length <= 0) {
      res.task.task_time = []
    } else {
      res.task.task_time = res.task.task_time.map((item: any) => {
        return {
          time: item
        }
      })
    }

    Object.assign(formData, res.task)
    console.log('formData: ', formData)
    formData.timeArr = res.task.task_time
    formData.month = res.task.collect_date
    formData.weekArr = res.task.collect_date
  })
}

onMounted(() => {
  reset()
  getCollectResources()
  taskId.value = router.currentRoute.value.query?.id as string
  console.log('taskId.value: ', taskId.value)
  if (!taskId.value) return false
  getTaskDetail()
})
</script>

<style lang="less" scoped>
.add-edit-timed-task-form {
  // width: 574px;
  margin-top: 24px;

  :deep(.ant-form-item-control) {
    margin-top: 4px;
  }

  .sort-input {
    width: 300px;
  }

  .month-input {
    margin-top: 8px;
    margin-bottom: 0;
  }

  .resource-type {
    .describe {
      font-size: 12px;
      color: #bfbfbf;
    }
  }

  .collect-type {
    .input-content {
      display: flex;
    }

    .describe {
      font-size: 12px;
      color: #bfbfbf;
      line-height: 20px;
    }
  }
}
</style>
